import { _decorator, find, instantiate, Label, math, Node, tween, UITransform, v2, v3, Vec2, Vec3, Widget } from 'cc';
import AssetMgr from '../frame/AssetMgr';
import { objPool } from './fish/objPool';
const { ccclass, property } = _decorator;

export class Tools {

    /** 获取带有 co 组件的所有子节点，移除这些节点 */
    static clearFromParent(node: Node, co: any) {
        let arr = [];
        node.children.forEach(element => {
            if (element.getComponent(co)) {
                arr.push(element);
            }
        });
        arr.forEach((element) => {
            element.removeFromParent();
        });

    }

    /** 返回此区间随机数 */
    static random_between(min: number, max: number): number {
        return Math.random() * (max - min) + min;
    }

    /** 打乱数组 */
    static shuffle(array) {
        for (let i = array.length - 1; i > 0; i--) {
            let j = Math.floor(Math.random() * (i + 1));
            [array[i], array[j]] = [array[j], array[i]];
        }
    }
    /** 打乱数组 */
    static shuffle2(array) {
        for (let i = 0; i < array.length; i++) {
            let j = Math.floor(Math.random() * array.length);
            [array[i], array[j]] = [array[j], array[i]];
        }
    }

    
    /** 计算角度(传入向量) */
    static getAngle(x1: Vec3, x2: Vec3) {
        //计算模长
        const amo = Math.sqrt((x1.x * x1.x) + (x1.y * x1.y));
        const bmo = Math.sqrt(x2.x * x2.x + x2.y * x2.y);
        //计算点积
        const abdot = x1.x * x2.x + x1.y * x2.y
        //计算余弦值
        const cossin = abdot/(amo * bmo)
        //弧度转角度toDegree(反余弦acos)
        let angle = math.toDegree(Math.acos(cossin))

        //计算叉积(判断正负)
        const cross = x1.x * x2.y + x1.y * x2.x
        if(cross > 0)angle *= -1;//ps：应该是小于0才为负数，测试 >0 才是正常的

        return angle;
    }

    static V3ToV2(v:Vec3){ return v2(v.x , v.y) }
    static V2ToV3(v:Vec2){ return v3(v.x , v.y , 0) }

    /** 场景适配width ， 分辨率不同时 height 会拉伸，返回 多出的 _height */
    static scene_height_extra(){
        const size = find('Canvas').getComponent(UITransform).contentSize;
        const _height = size.height - 1400;
        return _height;
    }

    /** 更新widget */
    static updateWidget(n:Node , btn_empty_close = false){
        n.setPosition(v3(0 , 0 , 0 ));
        n.getComponent(Widget).enabled = true
        n.getChildByName("mask").getComponent(Widget).enabled = true

        if(btn_empty_close)
            n.getChildByName("btn").getComponent(Widget).enabled = true;
    }

    /** 生成提示 */
    static async newTips(str:string){
        let tip_prefab = await AssetMgr.Inst.getOnePrefab("prefabs/tip" , "gameBundle");
        let _node = objPool.ins.getObj_prefab(tip_prefab)
        _node.setParent(find("Canvas"))
        _node.getChildByName("Label").getComponent(Label).string = str

        tween(_node).to(1, {position : v3(0,100,0)}).delay(2).call(()=>{
            objPool.ins.removeObj("tip",_node)
        }).start()
    }
}

